"""
    This module maintains GUI-list of collection directories.
"""
import pygtk
import gtk
import gobject
import os
import sys

from .. import exceptions
from .. import path
from .. import log
from .. import settings
from .. import core

# possible return values of run_dialog() function
LIST_NOT_UPDATED = 0
LIST_UPDATED = 1

parent = None

def initialize(parent_window):
    """
    Initialize module. parent has to be a top-level window of the application.
    """
    global parent

    if not parent is None:
        raise exceptions.InitializationError("Module already initialized!")

    parent = parent_window

def on_dir_add(widget, dialog, treeview):
    liststore = treeview.get_model()

    # open select directory dialog
    chooser = gtk.FileChooserDialog(_("Choose collection directory"),
        parent=dialog, action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
        buttons=None, backend=None)
    
    chooser.add_button(_("Cancel"), gtk.RESPONSE_CANCEL)
    chooser.add_button(_("Choose"), gtk.RESPONSE_ACCEPT)

    response = chooser.run()
    dir = chooser.get_filename()
    chooser.destroy()

    if gtk.RESPONSE_ACCEPT == response:
        # try to add directory to liststore
        # first check that `dir' is not part of any existing directory in list and vice versa
        iter = liststore.get_iter_first()
        dir_ok = True
        error_title = _("Please choose another directory")

        while not iter is None:
            value = liststore.get_value(iter, 0)
            if dir.startswith(value):
                # display warning: one of list entries already include selected dir
                core.error(("One of the list entries (%(entry)s) already include selected directory (%(directory)s)!") % {
                    'entry': value, 
                    'directory': dir
                    }, format=error_title, parent_window=dialog)
                dir_ok = False
                break

            elif value.startswith(dir):
                # display warning: selected directory contains one of the list's dir
                core.error(_("Selected directory (%(directory)s) includes one of the presented in the list!") % {
                    'directory': value}, format=error_title, parent_window=dialog)
                dir_ok = False
                break

            iter = liststore.iter_next(iter)
        
        if dir_ok:
            liststore.append([dir])
    
def on_dir_remove(widget, dialog, treeview):
    liststore = treeview.get_model()
    tm, iter = treeview.get_selection().get_selected()

    if not iter is None:
        liststore.remove(iter)


def run_dialog():
    if parent is None:
        raise exceptions.InitializationError("Module must be initialized before first use!")

    xml = gtk.glade.XML(path.get_data_path("pybookshelf.glade"), root="collection_dirs_dialog", 
                        domain="pybookshelf")
    dialog = xml.get_widget("collection_dirs_dialog")

    # get dialog size values
    width = settings.get_int("ui/cdirs_width")
    height = settings.get_int("ui/cdirs_height")

    # get list of collection directories and append them to the model
    collection_dirs = settings.get_list("collection/dirs")

    # create model
    liststore = gtk.ListStore(gobject.TYPE_STRING)
    [liststore.append([s]) for s in collection_dirs]

    treeview = xml.get_widget("dirs_list")
    column = gtk.TreeViewColumn(_("Directory"))
    cell = gtk.CellRendererText()
    column.pack_start(cell, True)
    column.add_attribute(cell, 'text', 0)
    treeview.append_column(column)
    treeview.set_model(liststore)

    # connect signals to dialog buttons
    add_button = xml.get_widget("add_button")
    add_button.connect("clicked", on_dir_add, dialog, treeview)

    remove_button = xml.get_widget("remove_button")
    remove_button.connect("clicked", on_dir_remove, dialog, treeview)

    

    dialog.resize(width, height)
    dialog.set_transient_for(parent)
    response = dialog.run()
    # response==0 if Cancel clicked
    # response==1 if Apply clicked

    # save dialog size
    width, height = dialog.get_size()
    dialog.destroy()

    settings.set_int("ui/cdirs_width", width)
    settings.set_int("ui/cdirs_height", height)

    state = LIST_NOT_UPDATED

    if response == 1:
        # check list contents has been changed
        new_collection_dirs = []
        iter = liststore.get_iter_first()

        while not iter is None:
            value = liststore.get_value(iter, 0)
            new_collection_dirs.append(value)
            iter = liststore.iter_next(iter)

        
        new_collection_dirs.sort()
        collection_dirs.sort()

        if len(new_collection_dirs) == len(collection_dirs):
            for i in range(len(new_collection_dirs)):
                if new_collection_dirs[i] != collection_dirs[i]:
                    state = LIST_UPDATED
                    break
        else:
            state = LIST_UPDATED

        if LIST_UPDATED == state:
            # save new list
            settings.set_list("collection/dirs", new_collection_dirs)

        log.debug(new_collection_dirs)
        log.debug(collection_dirs)

    return state
